#include "letteredit.h"
#include <QGridLayout>





//----------------------------------------
LetterEdit::LetterEdit(QWidget *parent) :
	QLineEdit(parent)
{
	setMaxLength (1);

	setFixedSize (30, 30);
	setAlignment (Qt::AlignCenter);
	QFont font;
	font.setBold (true);
	font.setCapitalization (QFont::AllUppercase);
	setFont (font);
	setContentsMargins (0,0,0,0);

	initMenu ();

	connect (this,
			 SIGNAL(textEdited(QString)),
			 this,
			 SLOT(onTextEdited(QString)));

	connect (this,
			 SIGNAL(customContextMenuRequested(QPoint)),
			 this,
			 SLOT(onCustomContextMenuRequested(QPoint)));
}
//------------------------
LetterEdit::~LetterEdit ()
{
	m_menu.clear ();
}
//--------------------------
void LetterEdit::initMenu ()
{
	QStringList letters;
	foreach (QString car, m_allowedCars ())
	{
		letters << car;
	}

	QList<QAction*> actionList;

	foreach (QString letter, letters)
	{
		QAction* action = new QAction (letter, this);
		actionList << action;
	}

	m_menu.addActions (actionList);

	setContextMenuPolicy (Qt::CustomContextMenu);

}
//---------------------------------------
void LetterEdit::setLetter (const QChar &car)
{
	setText (QString (car));
	emit letterChanged (letter ());
}
//------------------------------------------
void LetterEdit::onTextEdited (const QString &txt)
{
	if (!m_allowedCars ().contains (txt, Qt::CaseInsensitive))
	{
		undo ();
	}
	else
	{
		emit letterChanged (letter ());
	}

	selectAll ();
}
//--------------------------
QChar LetterEdit::letter ()
{
	if (text ().isEmpty ())
	{
		return Config::m_blankDisplay;
	}
	else
	{
		return text ().at (0).toUpper ();
	}
}
//---------------------------------------------------------------
void LetterEdit::onCustomContextMenuRequested (const QPoint &pos)
{
	QAction* action (m_menu.exec (mapToGlobal (pos)));	// ici tu as un pointeur sur l'item cliqué
	// ou 0 si clic en dehors du menu

	if (action == 0) return;

	setLetter (action->text ().at (0));
}
